package wendyeq.iweb.blog.web.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import wendyeq.iweb.blog.pojo.Category;
import wendyeq.iweb.blog.service.ICategoryService;
@Controller
@RequestMapping("/admin/category/")
public class CategoryController {
	private static final Logger logger = Logger
			.getLogger(CategoryController.class);

	@Resource(name="categoryServiceImpl")
	private ICategoryService categoryService;
	
	@RequestMapping("")
	public String addCategory(HttpServletRequest request) {
		return "admin/category";
	}
	
	@RequestMapping("post")
	public String postCategory(@RequestParam String name ,HttpServletRequest request, ModelMap model) {
		logger.warn("idd="+name+"----");
		this.categoryService.save(new Category(name));
		return "admin/category";
	}
	/***
	 * http://localhost:8888/admin/category/update?oldName=cctest&newName=cctes1
	 * */
	@RequestMapping("update")
	public String updateCategory(@RequestParam String oldName ,@RequestParam String newName, HttpServletRequest request, ModelMap model) {
		logger.warn("idd="+oldName+"----");
		logger.warn("newid="+newName+"----");
		this.categoryService.modify(oldName, newName);
		return "admin/category";
	}
	
	@RequestMapping("del/{id}")
	public String delCategory(@PathVariable String id, HttpServletRequest request, ModelMap model) {
		logger.warn(id);
		this.categoryService.delete(id);
		return "admin/category";
	}

	@RequestMapping("list/{page}")
	public String getAllCategory(@PathVariable int page,HttpServletRequest request , ModelMap model) throws IOException {
		logger.warn("Do getAllCategory");
		List<Category> categorys = this.categoryService.findAll();
		int catSize = categorys.size();
		if(catSize<15){
			model.addAttribute("categorys",categorys );
		}else if(categorys.size()-page*15>=0){
			model.addAttribute("categorys",categorys.subList((page-1)*15,page*15));
		}else {
			model.addAttribute("categorys",categorys.subList((page-1)*15,catSize));
		}
		model.addAttribute("catSize", categorys.size());
		model.addAttribute("page", page);
		return "admin/categoryList";
	}
	
}
